<?php
	 define('MANS_', true);

	 require(dirname(__FILE__) . '/includes/init.php');

	 $sm->setCaching(0);
	 $ajax = !empty($_POST['ajax']) ? $_POST['ajax'] : '';
	 $act  = !empty($_REQUEST['act'])  ?  $_REQUEST['act'] : 'dasai';
	 $page = !empty($_REQUEST['page'])? intval($_REQUEST['page']) : 0;
	 $size = !empty($_REQUEST['size']) ? intval($_REQUEST['size']) : 10;
	 $sm = $GLOBALS['smarty'];
	 $sm->assign('act',	$act);

	 //获取region
	 if($act=="get_region")
	 {
		$region_id = !empty($_POST['region_id'])? intval($_POST['region_id']) : 0;
		$region_list = $Main->getRegion($region_id);
		die(json_encode($region_list));
	 }
	 //增加收货人信息
	 elseif($act=='add_addr')
	 {

		$json = !empty($_POST['data']) ? stripcslashes($_POST['data']) : '';
		$addr = json_encode($User->addAddr($json));
		$_SESSION[USER_AGENT]['address'] = $addr;
		$res['list'] = $User->getAddrList($_SESSION['user_id']);
		$res['addr'] = $Main->json2Array($addr);

		die(json_encode($res));
	 }
	 //更新收货人信息
	 elseif($act=='update_addr')
	 {
		$data = !empty($_POST['data']) ? stripcslashes($_POST['data']) : '';
		$addr = $User->updateAddr($data);
		$_SESSION[USER_AGENT]['address'] = $addr;
		$res['list'] = $User->getAddrList($_SESSION['user_id']);
		$res['addr'] = $addr;

		die(json_encode($res));
	 }
	 //删除收货人信息
	 elseif($act=='del_addr')
	 {

		$address_id = !empty($_POST['address_id']) ? $_POST['address_id'] : 0;
		$User->DelAddr($address_id);
		$list =  $User->getAddrList($_SESSION['user_id']);
		$_SESSION[USER_AGENT]['address'] = @json_encode($list[0]['addr']);
		$res['list'] = $list;
		$res['addr'] = @$list[0]['addr'];

		die(json_encode($res));
	 }
	 //取得一条收货人信息
	 elseif($act=='get_addr')
	 {
		$address_id = !empty($_POST['address_id'])? intval($_POST['address_id']) : 0;
		$addr =$User->getAddr($address_id);
		die(json_encode($addr));
	 }

	 //设置收货人地址
	 elseif($act=="set_addr")
	 {
		$address_id = !empty($_POST['address_id'])? intval($_POST['address_id']) : 0;
		$addr =$User->getAddr($address_id);

		$_SESSION[USER_AGENT]['address'] = json_encode($addr);

		die(json_encode($addr));
	 }

	 //设置运费
	 elseif($act=="shipping")
	 {
		$shipping_id = !empty($_POST['shipping_id'])? intval($_POST['shipping_id']) : 0;
		$shipping = $Main->shippingOne($shipping_id);
		$cart_goods = $Order->cartGoods();
		$grand = $Order->grandTotal($cart_goods,$shipping);
		$_SESSION[USER_AGENT]['shipping'] = $shipping;
		die(json_encode($grand));
	 }
	 //支付方式
	 elseif($act=='payment')
	 {
		$pay_id = !empty($_POST['payment_id'])? intval($_POST['payment_id']) : 0;
		$_SESSION[USER_AGENT]['payment'] = $Main->paymentOne($pay_id);
		die('1');
	 }

	 //使用优惠码
	 elseif($act=='apply_discount')
	 {
		$code = !empty($_POST['code'])? $Main->escapeString($_POST['code']) : '';

		$discount = $Main->discountOne($code);

		if($discount)
		{
			$_SESSION[USER_AGENT]['discount'] = $discount;
		}
		else
		{
			$_SESSION[USER_AGENT]['discount'] = 0;
		}
		$cart_goods = $Order->cartGoods();
		$shipping = $Order->getShipping();
		$grand = $Order->grandTotal($cart_goods,$shipping);
		die(json_encode($grand));

	 }
	 //增加留言
	 elseif($act=="add_message")
	 {
		 $message = !empty($_POST['message'])? $Main->escapeString($_POST['message']) : '';
		 $_SESSION[USER_AGENT]['message'] = $message;
		 die('1');

	 }
	 //检查订单信息是否完整
	 elseif($act=="check_order")
	 {
		$data = !empty($_POST['data']) ? $Main->json2Array(stripcslashes($_POST['data'])) : '' ;

		$res = $Order->checkOrder($data);

		die(json_encode($res));
	 }
	 //删除购物车
	 elseif($act=="drop_cart")
	 {
		$rec_id = !empty($_POST['rec_id'])? intval($_POST['rec_id']) : 0;
		$res = $Order->dropCart($rec_id);

		die('1');
	 }

	 //动态或许最新产品
	 elseif($act=='ajax_goods_list')
	 {
		$cat_id = !empty($_POST['cat_id']) ? intval($_POST['cat_id']) : 0 ;
		$goods_list = $Goods->randGoods(array($cat_id),4);
		$goods_list = json_encode($goods_list);
		die($goods_list);
	 }
	 //增加到购物车
	 elseif($act=='add_cart')
	 {

		//购物车中只允许一个商品，所以，购买前，先删除
		mysql_query("delete from cart where session_id='".USER_AGENT."'");

		$data = !empty($_POST['data']) ? $Main->json2Array(stripcslashes($_POST['data'])) : '' ;
		$data['attrs'] = !empty($data['attrs']) ?  preg_split('/,/',$data['attrs']) : array();

		$Order->addToCart($data['goods_id'],$data['number'],$data['attrs']);
		die(json_encode($Order->getTopCart()));
	 }
	 elseif($act=='add_cart_many')
	 {
		$goods = !empty($_POST['goods']) ?$Main->json2Array(stripcslashes($_POST['goods'])) : array() ;

		$p_id = !empty($_POST['p_id']) ? intval($_POST['p_id']) : 0 ;

		foreach($goods as $key=>$val)
		{
			$goods_id = intval($val['goods_id']);
			$goods_number = intval($val['goods_number']);

			$Order->addToCart($goods_id,$goods_number,$val['attrs'],$p_id);
		}

		die(json_encode($Order->getTopCart()));
	 }
	 //取得商品价格
	 elseif ($act == 'get_price')
    {
		$g_id = !empty($_REQUEST['g_id']) ? intval($_REQUEST['g_id']) : 0;
		$goods = $Goods->goodsInfo($g_id);
		$price['shop_priced'] = $goods['shop_priced'];
		$price['market_priced'] = $goods['market_priced'];
		die(json_encode($price));
	}
	//更改属性价格
	elseif($act =='change_attr_price')
	{
		$goods_number = !empty($_POST['goods_number']) ? (int)$_POST['goods_number'] : 0;
		$goods_id     = !empty($_POST['goods_id']) ? $_POST['goods_id'] : 0;
		$attr_id     = !empty($_POST['attr_id']) ? $_POST['attr_id'] : 0;
		$attr_price = 0;
		if($attr_id)
		{
			$sp = preg_split("/,/",$attr_id);

			foreach($sp as $key=>$val)
			{
				$attr = $Goods->attrOne($val);
				$attr_price += $attr['attr_price'];
			}
		}
		$goods = $Goods->goodsBasic($goods_id);
		$price = $goods['shop_price']+$attr_price;

		$price = $price*$goods_number;

		die($Main->priceFormat($price));
	}
	//更改货币
	if($act=="change_currency")
	{
		if(!empty($_REQUEST['cur']))
		{
			$_SESSION['price_type']=$_REQUEST['cur'];
			die('1');
		}
		else
		{
			die('0');
		}
	}
	//更改购物车价格
	elseif($act =='change_cart_price')
	{

		$goods_number = !empty($_POST['goods_number']) ? intval($_POST['goods_number']) : 0;
		$rec_id     = !empty($_POST['rec_id']) ? intval($_POST['rec_id']) : 0;
		$sql = "update cart set goods_number=$goods_number where rec_id=$rec_id";
		mysql_query($sql);
		$cart_goods = $Order->cartGoods();

		die(json_encode($cart_goods));
	}
	//设置token
	elseif($act=='set_token')
	{
		if(!isset($_SESSION['token']))
		{
			$Main->setToken();
		}
		die($_SESSION['token']);
	}
	//创建用户
	elseif($act=='user_add')
	{
		$data = !empty($_POST['data']) ? $Main->json2Array(stripcslashes($_POST['data'])) : '' ;

		echo $User->addUser($data['email'],md5($data['passwd']));

	}
	//登陆
	elseif($act=='user_login')
	{
		$data = !empty($_POST['data']) ? $Main->json2Array(stripcslashes($_POST['data'])) : '' ;
		$r = $User->userLogin($data);

		if($r<0)
			die('-1');
		if($r)
		{
			$user = $_SESSION['user_info'];

			$login['user_id'] = $user['user_id'];
			$login['user_name'] = $user['user_name'];
			$login['add_time'] =  time();
			$GLOBALS['db']->autoExecute('login_log',$login);

			$url = !empty($_POST['return']) ? $_POST['return']: './';
			if(!empty($_POST['title']) && !empty($_POST['web']))
				$url = $url.'&title='.$_POST['title'].'&web='.$_POST['web'];
			die($url);
		}
		die('0');
	}

	//签到
	elseif($act=='qiandao')
	{

		//登陆加分，每天一次
		$user_id=$_SESSION['user_id'];
		$_SESSION['qiandao']=1;
		$g = 'u_'.$user_id;
		$last = $GLOBALS['db']->getOne("select add_time from gold_log where buyer='login' and geter='$g' order by add_time desc");

		$day_start = mktime(0,0,0,date("m"),date("d"),date("Y"));
		$day_end   = mktime(23,59,59,date("m"),date("d"),date("Y"));

		if($last<$day_start)
		{
			$return['return'] = $user_return = $GLOBALS['gold']['gold']['login']['gold'];
			$return['comment'] = '签到成功，系统返回'.($user_return).' 青币 给 '.$_SESSION['user_info']['user_name'].' 操作人:system';
			$return['user_id'] = $user_id;
			$return['buyer'] = 'login';
			$User->goldLogReturnUser($return);

			setCookie("user[$user_id][qiandao]",1,$day_end,'/ ');

			$order['un_review'] = $GLOBALS['db']->getOne("select count(*) as un_review from order_info where user_id=$user_id and review_id=0");
			$order['order_num'] = $GLOBALS['db']->getOne("select count(*) as order_num from order_info where user_id=$user_id");
			die(json_encode($order));

		}

		die('0');
		//print_r($_POST);die();
	}
	//自动登录
	elseif($act=='auto_login')
	{
		$data = !empty($_POST['data']) ? $Main->json2Array(stripcslashes($_POST['data'])) : '' ;

		echo $User->autoLogin($data);
		die();
	}
	//设置头像
	elseif($act=='set_avater')
	{
		$data['avater'] = !empty($_POST['avater']) ? $_POST['avater'] : '';
		echo $User->userEdit($data);
		die();
	}
	//用户修改密码
	elseif($act=='user_setting')
	{
		$res = 0;
		$data = !empty($_POST['data']) ? $Main->json2Array(stripcslashes($_POST['data'])) : '' ;
		$user_info = $User->userInfo($_SESSION['user_id']);
		if(md5($data['old_passwd'])==$user_info['passwd'])
		{
			$res = $User->userEdit($data);
		}
		echo $res;
		die();
	}
	//注销
	elseif($act=='log_out')
	{
		echo $User->logOut();
		die();
	}
	//找回密码
	elseif($act=='reset_passwd')
	{
		$email = !empty($_POST['email']) ? $_POST['email'] : '';

		if($User->isRegister($email))
		{
			$user = $User->userInfo2($email,'email');

			$new_pass = substr(md5(time().USER_AGENT),0,10);
			$tmp = $Main->mailTemplateOne('reset_passwd');
			$data['subject'] = $tmp['subject'];
			$data['to']      = array($email);
			$com = array($user['user_name'],$new_pass,$_CFG['shop_name'],$Main->dateFormat(time()));
			$data['body']    = sprintf($tmp['content'],$com[0],$com[1],$com[2],$com[3]);

			$msg =  ($User->userPasswdReset($email,md5($new_pass)) && $Main->sendMail($data));
		}
		else
		{
			$msg = 'Invalid Email';
		}
		die($msg);
	}
	//检查是否注册
	elseif($act=='is_register')
	{

		$user_name = !empty($_REQUEST['user_name']) ? $_REQUEST['user_name'] : '';
		$email = !empty($_REQUEST['email']) ? $_REQUEST['email'] : '';
		$value = $user_name ? $user_name : $email;
		$field = $user_name ? 'user_name' : 'email';

		if($field &&  $value)
		{

			$res = $User->isRegister($value,$field);
			die(json_encode($res));
		}
		die('0');


	}

	//文件上传
	elseif ($act == 'goods_img_upload') {

		$name = !empty($_GET['name']) ? $Main->buildUri($_GET['name'],-1).substr(time(),6,4) : '';
		$_SESSION['count']++;
		$res = $Main->uploader(UPLOAD_PATH .'/goods/', false, false,$name);

		die($res);
	}
	elseif ($act == 'uploader') {

		$path = !empty($_GET['path']) ? '/'.$_GET['path'].'/' : '/'.date('Ymd',time()).'/';
		$swfupload = !empty($_REQUEST['swfupload']) ? true : false;

		$res = $Main->uploader(UPLOAD_PATH . $path, false, false,'','Filedata',$swfupload);



		die($res);
	}
	elseif ($act == 'upload_ckeditor') {
		$sep = !empty($_GET['sep']) ? $_GET['sep'] : '.';
		$funcNum = @$_GET['CKEditorFuncNum'];

		$res = $Main->uploader(UPLOAD_PATH . '/upload/', false, false,'','upload');
		$res = $sep.'/'.$res;

		$message = '上传成功!';
		echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$res', '$message');</script>";
		die();
	}
	//文件删除
	elseif ($act == 'del_file') {
		$url = $_POST['url'];
		$url = preg_replace("/\.\.\//","",$url);
		echo unlink($url);
		die();
	}
	//发送邮件
	elseif($act=='send_mail')
	{
		$data = !empty($_POST['data']) ? $Main->json2Array(stripcslashes($_POST['data'])) : '' ;
		$file = is_array($data['file']) ? $data['file'] : array();
		$f = array();
		foreach($file as $key=>$val)
		{
			$url = preg_replace("/\.\.\//","",$val['url']);
			$f[] = $url;
		}
		$data['file'] = $f;
		$data['to'] = preg_split("/\;/",$data['to']);

		echo $Main->sendMail($data);
		die();
	}
	//取得邮件模板
	elseif($act=='get_email_template')
	{
		$code = !empty($_POST['code']) ? $_POST['code'] : '' ;
		$tem = $Main->mailTemplateOne($code);
		die(json_encode($tem));
	}
	//设置邮件模板
	elseif($act=='set_email_template')
	{
		$t_id = !empty($_POST['t_id']) ? intval($_POST['t_id']) : 0;
		$data = $Main->getPostData($_POST,array('act','t_id'));

		echo $GLOBALS['db']->autoExecute('mail_templates',$data,'update',' t_id='.$t_id);
		die();
	}
	//新增邮件模板
	elseif($act=='add_email_template')
	{
		$t_id = !empty($_POST['t_id']) ? intval($_POST['t_id']) : 0;
		$data = $Main->getPostData($_POST,array('act','t_id'));
		echo $GLOBALS['db']->autoExecute('mail_templates',$data);
		die();
	}
	//删除邮件模板
	elseif($act=='del_email_template')
	{
		$t_id = !empty($_POST['t_id']) ? intval($_POST['t_id']) : 0 ;
		echo $Main->mailTemplateDel($t_id);
		die();
	}
	//增加评论
	elseif($act=='add_review')
	{

		$data = !empty($_POST['data']) ? $Main->json2Array(stripcslashes($_POST['data'])) : '' ;
	    $order_id = !empty($_POST['order_id']) ? intval($_POST['order_id']) : 0;
	    $r_id = !empty($_POST['r_id']) ? intval($_POST['r_id']) : 0;
		if($data)
		{
			if($r_id && $GLOBALS['db']->autoExecute('review',$data,'update',"r_id=$r_id")) //修改
			{

				die('1');
			}

			$data['add_time'] = time();

			if($GLOBALS['db']->autoExecute('review',$data))
			{
				$review_id = mysql_insert_id();
				if($order_id)
				{
					//购买商品后评价积分
					//$User->orderGold($data['id'],$order_id,$data['score'],$review_id);
				}

				$User->sendMailNotice($data);

				die('1');
			}
		}

		die('0');
	}
	//设置屏幕分辨率
	elseif($act=='set_screen')
	{
		$_SESSION['screen'] = !empty($_POST['val']) ? intval($_POST['val']) : 0 ;
		if($_SESSION['screen']>=1300)
		{
			$_SESSION['style'] = 130;
		}
		else
		{
			$_SESSION['style'] = '';
		}
		die();
	}
	//更改原图
	elseif ($act == 'change_ori') {
		$goods_id = !empty($_POST['goods_id']) ? intval($_POST['goods_id']) : 0;
		$src = !empty($_POST['src']) ? mysql_real_escape_string($_POST['src']) : 0;
		$res = $Goods->asOriginal($goods_id, $src);
		die($res);
	}
	//价格区间
	elseif($act=='price_limit')
	{
		$price = $_POST['price'];
		$s = preg_split("/-/",$price);
		$st = intval($s[0]);
		$en = intval($s[1]);
		$l['start'] = $st;
		$l['end'] = $en;
		$ld['start'] = $Main->priceFormat($st);
		$ld['end'] = $Main->priceFormat($en);
		$_SESSION['search']['price_limit'] = $l;
		$_SESSION['search']['price_limitd'] = $ld;
		die('1');
	}
	//赞
	elseif($act=='zan')
	{
		$data['id'] = $id =  !empty($_POST['id']) ? intval($_POST['id']) : 0;
		$data['type'] = $type = !empty($_POST['type']) ? intval($_POST['type']) : 0;
		$data['ip'] = $ip =  $_SERVER['REMOTE_ADDR'];
        $data['add_time'] = time();
		$data['user_name'] =$user_name =  $_SESSION['oauser'];
		$count = $Main->counts("select count(*) from zan where user_name ='$user_name' and  type='$type'");
		if($count>5)
		{
			$res['err'] = 1;
			$res['msg'] = '您的投资数已超过5次';
			die(json_encode($res));
		}
		if(!$Main->counts("select count(*) from zan where user_name ='$user_name' and ip='$ip' and type='$type' and id='$id'"))
		{
			$GLOBALS['db']->autoExecute('zan',$data);
			$res['zan'] = $Main->counts("select count(*) from zan where type='$type' and id='$id'");
			$res['id'] = ''.$id;
			$res['err'] = 0;
			$res['msg'] = '投资成功';
			die(json_encode($res));

		}
		else
		{
			$res['err'] = 1;
			$res['msg'] = '您已经投资过了';
			die(json_encode($res));
		}


	}
	//cat_log
	elseif($act=='add_cat_log')
	{
		$data = !empty($_POST['data']) ? $Main->json2Array(stripcslashes($_POST['data'])) : '' ;
		$data['add_time'] = time();
		$data['content'] = strip_tags($data['content'],"<img>");

		if($GLOBALS['db']->autoExecute('cat_log',$data))
		{
			$g='c_'.$data['cat_id'];
			$last = $GLOBALS['db']->getOne("select add_time from gold_log where type=3 and buyer='cat_log' and geter='$g' order by add_time desc");

			if(!($last>=strtotime("-1 day") && $last<=strtotime("+1 day")))
			{
				$return['return'] = $user_return = $GLOBALS['gold']['gold']['cat_log']['gold'];
				$return['comment'] = '发布日志，系统返回'.($user_return).' 青币 操作人:'.$_SESSION['user_info']['user_name'];
				$return['cat_id'] = $data['cat_id'];
				$return['buyer'] = 'cat_log';
				$User->goldLogReturnCat($return);
			}
			die('1');
		}

		die('0');
	}
	//分配金币
	elseif($act=='send_gold')
	{
		$user_id = $_SESSION['user_id'];
		$data = !empty($_POST['data']) ? $Main->json2Array(stripcslashes($_POST['data'])) : '' ;
		$order_status = !empty($_POST['order_status']) ? 1 : 0 ;
		$res = $User->sendGold($data);
		if($order_status && $res)
		{
			$key = md5($user_id);
			$_SESSION['order_code'][$key] = md5('order_code'.time().$user_id);
			echo $_SESSION['order_code'][$key];
			die();
		}
		echo $res;

		die();

	}

	//修改cat_content
	elseif($act=='cat_content')
	{
		$cat_id = !empty($_POST['cat_id']) ? intval($_POST['cat_id']) : 0 ;
		$data['cat_content'] = !empty($_POST['cat_content']) ? $_POST['cat_content'] : '' ;
		if($GLOBALS['db']->autoExecute('category',$data,'update',"cat_id=$cat_id"))
		{
			die('1');
		}
		die('0');

	}
	//在线聊天
	elseif($act=='chat_send')
	{

		$data = !empty($_POST) ? $_POST : '';
		unset($data['act']);

		$Chat->chatSend($data);
		die();
	}
	elseif($act=='chat_get')
	{
		$c_id = !empty($_POST['c_id']) ? intval($_POST['c_id']) : 0;
		$pd_id = !empty($_POST['pd_id']) ? intval($_POST['pd_id']) : 0;
		$q_id = !empty($_POST['q_id']) ? intval($_POST['q_id']) : 0;
		$where = " where c_id>$c_id and q_id=$q_id";
		$data = $Chat->chatGetOne($where);
		$res['data'] = $data;
		//$res['chat_stop'] = $stop_user = $cate->chatStopUserGet();

		die(json_encode($res));
	}



?>
